
package cn.hpclub.server.service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;

import cn.hpclub.server.model.*;
import cn.hpclub.server.model.Package;
import cn.hpclub.server.util.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONArray;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;

import cn.hpclub.server.constant.Constant;
import cn.hpclub.server.model.product.Product;
import cn.hpclub.server.util.DateKit;
import cn.hpclub.server.util.InterfaceUtil;
import cn.hpclub.server.util.QueryHelper;

/**
 * @FileName: PromotionService.java
 * @Author zhl
 * @Description:首页弹窗信息Service
 * @Date 2016年6月27日 下午2:38:57
 * @CopyRight ZTE Corporation
 */
public class BusinessAuthConfigService{

    public static final String              OPERATION_ADD        = "add";
    public static final String              OPERATION_EDIT       = "edit";

    public static final int                 TYPE_CITY            = 1;
    public static final int                 TYPE_STORE           = 2;
    public static final int                 TYPE_MEMBER          = 3;
    public static final int                 TYPE_CHANNEL_CLASS   = 4;
    public static final int                 TYPE_CHANNEL_CLUSTER = 5;
    public static final int                 TYPE_CHANNEL_TYPE    = 6;
    private static final Logger             logger               = LoggerFactory
            .getLogger(BusinessAuthConfigService.class);
    public static BusinessAuthConfigService service              = new BusinessAuthConfigService();

    public List<Record> getBusinessTypeList(){
        List<Record> list = SysCodeType.dao.getCodeValueByTypeCode("HDLX");
//        List<Record> broadbandlist = SysCodeType.dao.getCodeValueByTypeCode("XYYW");
//        list.addAll(broadbandlist);
        List<Record> businessTypeList = SysCodeType.dao
                .getCodeValueByTypeCode(Constant.GENERAL_MEMBER_BUS_TYPE_SYS_CODE);
        list.addAll(businessTypeList);
        return list;
    }

    /**
     * 
     * @Title: getSqlSelect
     * @Description:取已授权业务数据列表时封装脚本时用，注意：业务授权和泛店员业务授权功能模块都使用了该方法，若有修改，请注意单独再写方法
     * @return String
     */
    public String getSqlSelect(){
        /*
         * String selectSql = "SELECT " + "sys_code.`NAME` as type_name," +
         * "t.name," + "o.DisplayName ," + "bac.creator_org_id," +
         * "bac.config_business_id,bac.config_business   ";
         */
        String selectSql = "SELECT * ";
        return selectSql;
    }

    public String getSqlExceptSelect(ConcurrentHashMap<String, String> searchInfo){
        String sqlExceptSelect = "FROM (SELECT sys_code.`NAME` AS type_name,t. name,o.DisplayName,bac.creator_org_id,"
                + "bac.config_business_id,bac.config_business FROM business_auth_config bac "
                + " LEFT JOIN tariff t ON bac.config_business_id = t.id" +
                // " LEFT JOIN tariff_class_relation tcr ON t.id=tcr.tariff_id "
                // +
                // " LEFT JOIN tariff_class tc ON tcr.tariff_class_id=tc.id "+
        "  LEFT JOIN( SELECT sv. NAME,sv.VALUE FROM sys_code_value sv "
                + " LEFT JOIN sys_code_type st ON st.id = sv.type_id WHERE st.`code` = 'HDLX' AND st.is_deleted = 0"
                + " AND sv.is_deleted = 0) as sys_code ON bac.config_business=sys_code.`VALUE` "
                + " LEFT JOIN organization o ON bac.creator_org_id=o.id  WHERE 1=1 "
                + " AND t.enabled=1 AND t.is_deleted=0 " + " AND t.end_date >= CURDATE()";
        // " AND tc.enabled=1

        for(Entry<String, String> item : searchInfo.entrySet()){
            sqlExceptSelect += buildQuery(item);
        }
        sqlExceptSelect += " GROUP BY bac.config_business_id,bac.creator_org_id) as table_s";
        return sqlExceptSelect;
    }

    /**
     * @Title: getSqlExceptSelectForSpreadMemberBusinessType
     * @Description:店长店员业务授权：获取资费类除外的已配置列表，如选号入网，营销活动选号入网。
     * @param searchInfo
     * @param businessType
     * @return String
     */
    public String getSqlExceptSelectForOtherBusiness(ConcurrentHashMap<String, String> searchInfo,
                                                     int businessType){
        String sqlExceptSelect = " FROM (";

        sqlExceptSelect += getSqlExceptSelect4GeneralAuth(searchInfo, businessType);


        sqlExceptSelect += ") AS table_s ORDER BY creator_org_id ASC,updated_time DESC";

        return sqlExceptSelect;
    }

    public String getSqlExceptSelectForBroadband(ConcurrentHashMap<String, String> searchInfo){
        String sqlExceptSelect = "FROM (SELECT sys_code.`NAME` AS type_name,t. name,o.DisplayName,bac.creator_org_id,bac.config_business_id,bac.config_business  FROM business_auth_config bac LEFT JOIN broadband t ON bac.config_business_id = t.id "
                + "  LEFT JOIN( SELECT sv. NAME,sv.VALUE FROM sys_code_value sv "
                + " LEFT JOIN sys_code_type st ON st.id = sv.type_id WHERE st.`code` = 'XYYW' AND st.is_deleted = 0"
                + " AND sv.is_deleted = 0) as sys_code ON bac.config_business=sys_code.`VALUE`  "
                + " LEFT JOIN organization o ON bac.creator_org_id=o.id  " + " WHERE 1=1 ";
        for(Entry<String, String> item : searchInfo.entrySet()){
            sqlExceptSelect += buildQuery(item);
        }
        sqlExceptSelect += " GROUP BY bac.config_business_id,bac.creator_org_id) as table_s ";
        return sqlExceptSelect;
    }

    /**
     * 
     * @Title: buildQuery
     * @Description:业务授权中获取或者查询已授权列表时用到的查询条件封装
     * @param item
     * @return String
     */
    private String buildQuery(Entry<String, String> item){
        if("list_select_type".equalsIgnoreCase(item.getKey())){
            return " and bac.config_business =" + item.getValue();
        }
        if("org_id".equalsIgnoreCase(item.getKey())){
            return " and bac.creator_org_id in("
                    + InterfaceUtil.getChlidOrgIdSql(Integer.parseInt(item.getValue()), Constant.MAX_ORG_LEVEL, true)
                    + ") ";
        }
        if("name".equalsIgnoreCase(item.getKey()) && StrKit.notBlank(item.getValue())){
            return " and t.name like '%" + item.getValue() + "%'";
        }
        return " ";
    }

    public int deleteBusinessAuthConfig(int config_business_id, int creator_org_id){
        String sql = "DELETE FROM business_auth_config WHERE config_business_id=? AND creator_org_id=?";
        int result = Db.update(sql, config_business_id, creator_org_id);
        return result;
    }

    public int deleteAuthorizationByPrimaryKey(int id){
        String sql = "DELETE FROM business_auth_config WHERE id=?";
        int result = Db.update(sql, id);
        return result;
    }

    public String createFlowId(){
        Date date = new Date();
        String dateStr = DateKit.toStr(date, "yyMMddHHmmss");

        StringBuffer buffer = new StringBuffer();
        Random random = new Random();
        for(int i = 0; i < 5; i++){// 添加5个数字
            buffer.append(random.nextInt(10));
        }

        return dateStr + buffer.toString();
    }

    public Page<Record> getChannel(int type, int pageNumber, int pageSize, ConcurrentHashMap<String, String> map){
        QueryHelper helper = new QueryHelper("select *", Constant.Table.ORGANIZATION_CLASS, "oc");
        helper.addCondition("oc.level=?", type - 3);// type-3正好是其层级
        String exact = map.get("queryType");
        helper.addCondition(map.containsKey("keyword") && !"exact".equals(exact),
                            "(oc.class_name like ? or oc.WebsiteId LIKE ?)", "%" + map.get("keyword") + "%",
                            "%" + map.get("keyword") + "%");
        helper.addCondition(map.containsKey("keyword") && "exact".equals(exact), "(oc.class_name= ? or oc.WebsiteId=?)",
                            map.get("keyword"), map.get("keyword"));
        Page<Record> page = Db.paginate(pageNumber, pageSize, helper.getSelect(), helper.getSqlExceptSelect());
        return page;
    }

    public Page<Record> getCity(int pageNumber, int pageSize, ConcurrentHashMap<String, String> map, String operation,
            int configBusinessId, int creatorOrgId, String flowId){
        QueryHelper helper = new QueryHelper("SELECT *", Constant.Table.ORGANIZATION, "org");
        helper.addCondition("org.CityCode=org.id ");
        helper.addCondition("org.id in " + InterfaceUtil.getChlidOrgIdSql(InterfaceUtil.getOrgId(), 1, true));

        if(OPERATION_EDIT.equalsIgnoreCase(operation)){
            helper.addCondition("org.id not in(select config_type_id from business_auth_config WHERE config_type=1 AND config_business_id=? and creator_org_id=? ) ",
                                configBusinessId, creatorOrgId);
        } else if(OPERATION_ADD.equalsIgnoreCase(operation)){
            helper.addCondition("org.id not in(SELECT config_type_id from business_auth_config_temp con WHERE config_type=1 AND flow_id=?)",
                                flowId);
        }
        String exact = map.get("queryType");
        helper.addCondition(map.containsKey("keyword") && !"exact".equals(exact), "(org.DisplayName LIKE ?)",
                            "%" + map.get("keyword") + "%");
        helper.addCondition(map.containsKey("keyword") && "exact".equals(exact), "(org.DisplayName = ?)",
                            map.get("keyword"));
        Page<Record> page = Db.paginate(pageNumber, pageSize, helper.getSelect(), helper.getSqlExceptSelect());
        return page;
    }

    public Page<Record> getStore(int pageNumber, int pageSize, ConcurrentHashMap<String, String> map){
        QueryHelper helper = new QueryHelper("SELECT org.*", Constant.Table.ORGANIZATION, "org");
        /* helper.addCondition("org.parentid=org.AreaCode"); */
        // helper.addCondition("org.parentid>0");
        helper.addCondition(" AreaCode = parentid");
        helper.addCondition(" AreaCode != 0");
        helper.addCondition("org.id in " + InterfaceUtil.getChlidOrgIdSql(InterfaceUtil.getOrgId(), Constant.MAX_ORG_LEVEL, true));
        helper.addCondition("org.is_deleted=0");
        String exact = map.get("queryType");
        helper.addCondition(map.containsKey("keyword") && !"exact".equals(exact), "(org.DisplayName LIKE ? or org.NumCode LIKE ?)","%" + map.get("keyword") + "%","%" + map.get("keyword") + "%");
        helper.addCondition(map.containsKey("keyword") && "exact".equals(exact), "(org.DisplayName = ? or org.NumCode = ?)", map.get("keyword"),map.get("keyword"));
        Page<Record> page = Db.paginate(pageNumber, pageSize, helper.getSelect(), helper.getSqlExceptSelect());
        return page;
    }

    public Page<Record> getMember(int pageNumber, int pageSize, ConcurrentHashMap<String, String> map){
        QueryHelper helper = new QueryHelper("select mo.id,mo.name,mo.emp_code,mo.mobile", Constant.Table.MEMBER_ORG,
                "mo");
        String orgFilter = InterfaceUtil.getChlidOrgIdSql(InterfaceUtil.getOrgId(), Constant.MAX_ORG_LEVEL, true);
        helper.addCondition("mo.org_id IN" + orgFilter);
        helper.addCondition("mo.enabled=1");
        helper.addCondition("mo.is_deleted=0");
        helper.addCondition("mo.member_type!=3");
        helper.addCondition(map.containsKey("keyword"), "(mo.name like ? or mo.user_name =? or mo.mobile=?)",
                            "%" + map.get("keyword") + "%", map.get("keyword"), map.get("keyword"));
        Page<Record> page = Db.paginate(pageNumber, pageSize, helper.getSelect(), helper.getSqlExceptSelect());
        return page;
    }

    public Page<Record> queryChannelTypeTemp(int pageNumber, int pageSize, ConcurrentHashMap<String, String> map,
            String flowId){
/*
        QueryHelper helper = new QueryHelper("select *", Constant.Table.ORGANIZATION_CLASS, "oc");
        helper.addCondition("oc.id IN(SELECT config_type_id FROM business_auth_config_temp WHERE config_type=? AND flow_id=?)",
                            BusinessAuthConfigService.TYPE_CHANNEL_TYPE, flowId);
        // helper.addCondition(map.containsKey("channelType"), "oc.class_name
        // like ? or
        // oc.WebsiteId=?",map.get("channelType"),map.get("channelType"));
        helper.addCondition(map.containsKey("keywordChannelType"), "(oc.class_name LIKE ? OR oc.WebsiteId=?)",
                            "%" + map.get("keywordChannelType") + "%", map.get("keywordChannelType"));
        Page<Record> page = Db.paginate(pageNumber, pageSize, helper.getSelect(), helper.getSqlExceptSelect());
*/


        QueryHelper helper = new QueryHelper(" SELECT oc.WebsiteId,oc.class_name,bac.id,org.DisplayName",
                " business_auth_config_temp bac  LEFT JOIN  " + " organization_class oc ON bac.config_type_id=oc.id   LEFT JOIN organization org on bac.city_org_id=org.id");
        helper.addCondition("bac.config_type=? AND bac.flow_id=? ",BusinessAuthConfigService.TYPE_CHANNEL_TYPE,flowId);
        helper.addCondition(map.containsKey("keywordChannelType"), " (oc.WebsiteId=? OR oc.class_name LIKE ? )",
                map.get("keywordChannelType"), "%" + map.get("keywordChannelType") + "%");
        Page<Record> page = Db.paginate(pageNumber, pageSize, helper.getSelect(), helper.getSqlExceptSelect());
        return page;
    }

    public Page<Record> queryChannelClusterTemp(int pageNumber, int pageSize, ConcurrentHashMap<String, String> map,
            String flowId){
/*
        QueryHelper helper = new QueryHelper("select *", Constant.Table.ORGANIZATION_CLASS, "oc");
        helper.addCondition("oc.id IN(SELECT config_type_id FROM business_auth_config_temp WHERE config_type=? AND flow_id=?)",
                            BusinessAuthConfigService.TYPE_CHANNEL_CLUSTER, flowId);
        helper.addCondition(map.containsKey("keywordChannelCluster"), "(oc.class_name LIKE ? OR oc.WebsiteId=?)",
                            "%" + map.get("keywordChannelCluster") + "%", map.get("keywordChannelCluster"));
        Page<Record> page = Db.paginate(pageNumber, pageSize, helper.getSelect(), helper.getSqlExceptSelect());
*/

        QueryHelper helper = new QueryHelper(" SELECT oc.WebsiteId,oc.class_name,bac.id,org.DisplayName",
                " business_auth_config_temp bac  LEFT JOIN  " + " organization_class oc ON bac.config_type_id=oc.id   LEFT JOIN organization org on bac.city_org_id=org.id");
        helper.addCondition("bac.config_type=? AND bac.flow_id=? ",BusinessAuthConfigService.TYPE_CHANNEL_CLUSTER,flowId);
        helper.addCondition(map.containsKey("keywordChannelCluster"), " (oc.WebsiteId=? OR oc.class_name LIKE ? )",
                map.get("keywordChannelCluster"), "%" + map.get("keywordChannelCluster") + "%");
        Page<Record> page = Db.paginate(pageNumber, pageSize, helper.getSelect(), helper.getSqlExceptSelect());
        return page;
    }

    public Page<Record> queryChannelClassTemp(int pageNumber, int pageSize, ConcurrentHashMap<String, String> map,
            String flowId){
        /*QueryHelper helper = new QueryHelper("select *", Constant.Table.ORGANIZATION_CLASS, "oc");
        helper.addCondition("oc.id IN(SELECT config_type_id FROM business_auth_config_temp WHERE config_type=? AND flow_id=?)",
                            BusinessAuthConfigService.TYPE_CHANNEL_CLASS, flowId);
        helper.addCondition(map.containsKey("keywordChannelClass"), "(oc.class_name LIKE ? OR oc.WebsiteId=?)",
                            "%" + map.get("keywordChannelClass") + "%", map.get("keywordChannelClass"));
        Page<Record> page = Db.paginate(pageNumber, pageSize, helper.getSelect(), helper.getSqlExceptSelect());*/

        QueryHelper helper = new QueryHelper(" SELECT oc.WebsiteId,oc.class_name,bac.id,org.DisplayName",
                " business_auth_config_temp bac  LEFT JOIN  " + " organization_class oc ON bac.config_type_id=oc.id   LEFT JOIN organization org on bac.city_org_id=org.id");
        helper.addCondition("bac.config_type=? AND bac.flow_id=? ",BusinessAuthConfigService.TYPE_CHANNEL_CLASS,flowId);
        helper.addCondition(map.containsKey("keywordChannelClass"), " (oc.WebsiteId=? OR oc.class_name LIKE ? )",
                map.get("keywordChannelClass"), "%" + map.get("keywordChannelClass") + "%");
        Page<Record> page = Db.paginate(pageNumber, pageSize, helper.getSelect(), helper.getSqlExceptSelect());
        return page;
    }

    public Page<Record> queryChannelMemberTemp(int pageNumber, int pageSize, ConcurrentHashMap<String, String> map,
            String flowId){
        QueryHelper helper = new QueryHelper("select *", Constant.Table.MEMBER_ORG, "mo");
        helper.addCondition("mo.id IN(SELECT config_type_id FROM business_auth_config_temp WHERE config_type=? AND flow_id=?)",
                            BusinessAuthConfigService.TYPE_MEMBER, flowId);
        helper.addCondition(map.containsKey("keywordMember"), "(mo.name LIKE ? OR mo.emp_code=? OR mo.mobile=?)",
                            "%" + map.get("keywordMember") + "%", map.get("keywordMember"), map.get("keywordMember"));
        Page<Record> page = Db.paginate(pageNumber, pageSize, helper.getSelect(), helper.getSqlExceptSelect());
        return page;
    }

    public Page<Record> queryChannelStoreTemp(int pageNumber, int pageSize, ConcurrentHashMap<String, String> map,
            String flowId){
        QueryHelper helper = new QueryHelper("select *", Constant.Table.ORGANIZATION, "org");
        helper.addCondition("org.id IN(SELECT config_type_id FROM business_auth_config_temp WHERE config_type=? AND flow_id=?)",
                            BusinessAuthConfigService.TYPE_STORE, flowId);
        helper.addCondition(map.containsKey("keywordOrg"), "(org.DisplayName LIKE ? OR org.NumCode=?)",
                            "%" + map.get("keywordOrg") + "%", map.get("keywordOrg"));
        Page<Record> page = Db.paginate(pageNumber, pageSize, helper.getSelect(), helper.getSqlExceptSelect());
        return page;
    }

    public Page<Record> queryChannelCityTemp(int pageNumber, int pageSize, ConcurrentHashMap<String, String> map,
            String flowId){
        QueryHelper helper = new QueryHelper("select *", Constant.Table.ORGANIZATION, "org");
        helper.addCondition(map.containsKey("keywordCity"), "(org.DisplayName LIKE ? OR org.NumCode=?)",
                            "%" + map.get("keywordCity") + "%", map.get("keywordCity"));
        helper.addCondition("org.id IN(SELECT config_type_id FROM business_auth_config_temp WHERE config_type=? AND flow_id=?)",
                            BusinessAuthConfigService.TYPE_CITY, flowId);
        Page<Record> page = Db.paginate(pageNumber, pageSize, helper.getSelect(), helper.getSqlExceptSelect());
        return page;
    }

    /**
     * 删除临时表数据
     * 
     * @param type
     * @param flow_id
     * @param ids
     * @return
     */
    public boolean deleteByTypeTemp(int type, String flow_id, Integer[] ids){
        StringBuffer sb = new StringBuffer();
        if(TYPE_CHANNEL_TYPE == type ||
                TYPE_CHANNEL_CLUSTER == type ||
                TYPE_CHANNEL_CLASS == type ){//由于设计的原因，新增的新增的id是实体的id（但是渠道的三个是授权表的id），编辑的新增的id的授权表的id
            sb.append("DELETE FROM " + Constant.Table.TABLE_BUSINESS_AUTH_CONFIG_TEMP + " WHERE "
                    + BusinessAuthConfig.FLOW_ID + "=" + flow_id + " AND " + BusinessAuthConfig.CONFIG_TYPE + "=" + type
                    + " AND id IN(");
        }else {
            sb.append("DELETE FROM " + Constant.Table.TABLE_BUSINESS_AUTH_CONFIG_TEMP + " WHERE "
                    + BusinessAuthConfig.FLOW_ID + "=" + flow_id + " AND " + BusinessAuthConfig.CONFIG_TYPE + "=" + type
                    + " AND " + BusinessAuthConfig.CONFIG_TYPE_ID + " IN(");
        }
        if(ids.length > 0){
            for(int i = 0; i < ids.length; i++){
                if(i == ids.length - 1){
                    sb.append("?");
                } else{
                    sb.append("?,");
                }
            }
            sb.append(")");
        } else{
            return false;
        }
        return Db.update(sb.toString(), (Object[])ids) > 0;
    }

    public boolean deleteByChannelTemp(Integer[] ids){
        StringBuffer sb = new StringBuffer();
        sb.append("DELETE FROM " + Constant.Table.TABLE_BUSINESS_AUTH_CONFIG_TEMP + " WHERE id IN(");
        if(ids.length > 0){
            for(int i = 0; i < ids.length; i++){
                if(i == ids.length - 1){
                    sb.append("?");
                } else{
                    sb.append("?,");
                }
            }
            sb.append(")");
        } else{
            return false;
        }
        return Db.update(sb.toString(), (Object[])ids) > 0;
    }

    /**
     * 删除正式表数据
     * 
     * @param
     * @param ids
     * @return
     */
    public boolean deleteByType(Integer[] ids){
        /*StringBuffer sb = new StringBuffer();
        sb.append("DELETE FROM " + Constant.Table.TABLE_BUSINESS_AUTH_CONFIG + " WHERE id in(");
        if(ids.length > 0){
            for(int i = 0; i < ids.length; i++){
                if(i == ids.length - 1){
                    sb.append("?");
                } else{
                    sb.append("?,");
                }
            }
            sb.append(")");
        } else{
            return false;
        }
        return Db.update(sb.toString(), (Object[])ids) > 0;*/
        String sql = "DELETE FROM " + Constant.Table.TABLE_BUSINESS_AUTH_CONFIG + " WHERE id in( %s )";
        return  Db.update(String.format(sql, Utils.join(ids,","))) > 0;
    }


    public boolean saveByType(int type, Integer[] ids, int business, int businessId, int creatorOrgId,Integer[] citys){
        for(int id : ids){
            // 查询数据是否已存在，存在就直接跳过
            if(TYPE_CHANNEL_TYPE == type){
                for (Integer cityOrgId : citys) {
                    BusinessAuthConfig.dao.saveAConfig(type, id, business, businessId,cityOrgId);
                }
            }else if(TYPE_CHANNEL_CLASS ==type || TYPE_CHANNEL_CLUSTER ==type){//渠道大类和渠道簇目前没加地市限制，所以由后台获取地市（省级获取21个地市，地市级获取自己），以后如果加上了，就可以跟渠道小类统一，由前端传来
                int my_org_id = InterfaceUtil.getOrgId();
                List<Organization> cityList = Organization.dao.getOrganizationCityList(my_org_id);
                for (Organization org:cityList){
                    BusinessAuthConfig.dao.saveAConfig(type, id, business, businessId,org.getInt(Organization.ID));
                }
            }else {
                BusinessAuthConfig.dao.saveAConfig(type, id, business, businessId,0);
            }
        }
        return true;
    }

    /**
     * 保存配置数据，从临时表来和参数组合
     * 
     * @param business
     * @param flowId
     * @param ids
     */
    public boolean saveConfig(int business, String flowId, Integer[] ids){
        int creator_org_id = InterfaceUtil.getOrgId();
        Date now = new Date();
        // 1.1获取临时表保存的type和type_id，如果没有就不让保存
        List<Record> records = Db.find("SELECT * FROM " + Constant.Table.TABLE_BUSINESS_AUTH_CONFIG_TEMP + " WHERE "
                + BusinessAuthConfig.FLOW_ID + "=" + flowId);
        if(null == records || records.size() == 0){
            return false;
        }
        // 2.删除原来的
        // String deleteSQL = "DELETE FROM
        // "+Constant.Table.TABLE_BUSINESS_AUTH_CONFIG+" WHERE
        // "+BusinessAuthConfig.CREATOR_ORG_ID+"=? AND
        // "+BusinessAuthConfig.CONFIG_BUSINESS+"=? AND
        // "+BusinessAuthConfig.CONFIG_BUSINESS_ID+"=?";
        // for(int id:ids){
        // Db.update(deleteSQL,creator_org_id,business,id);
        // }
        // 3.一条一条插入
        for(int id : ids){
            for(Record record : records){
                int city_org_id = record.getInt(BusinessAuthConfig.CITY_ORG_ID);
                BusinessAuthConfig.dao.saveAConfig(record.getInt(BusinessAuthConfig.CONFIG_TYPE),
                        record.getInt(BusinessAuthConfig.CONFIG_TYPE_ID), business, id,city_org_id);
            }
        }
        // 3.删除临时表数据，防止数据量太大
        // 不删除，因为可能保存之后还想另外再选择保存，比如大类：Db.update("DELETE FROM
        // "+Constant.Table.TABLE_BUSINESS_AUTH_CONFIG_TEMP + " WHERE
        // "+BusinessAuthConfig.FLOW_ID+"=?",flowId);
        return true;
    }

    /**
     * 获取已经配置的业务
     * 
     * @param business
     * @return
     */
    public Map<Integer, List<Record>> getConfigByBusiness(int business){
        List<Record> cityRecords = getConfigByBusiness(business, TYPE_CITY);
        List<Record> storeRecords = getConfigByBusiness(business, TYPE_STORE);
        List<Record> memberRecords = getConfigByBusiness(business, TYPE_MEMBER);
        List<Record> channelClassRecords = getConfigByBusiness(business, TYPE_CHANNEL_CLASS);
        List<Record> channelClusterRecords = getConfigByBusiness(business, TYPE_CHANNEL_CLUSTER);
        List<Record> channelTypeRecords = getConfigByBusiness(business, TYPE_CHANNEL_TYPE);
        Map<Integer, List<Record>> map = new HashMap<Integer, List<Record>>();
        map.put(TYPE_CITY, cityRecords);
        map.put(TYPE_STORE, storeRecords);
        map.put(TYPE_MEMBER, memberRecords);
        map.put(TYPE_CHANNEL_CLASS, channelClassRecords);
        map.put(TYPE_CHANNEL_CLUSTER, channelClusterRecords);
        map.put(TYPE_CHANNEL_TYPE, channelTypeRecords);
        return map;
    }

    /**
     * 根据业务类型和配置类型获取配置数据
     * 
     * @param business
     * @param type
     * @return
     */
    public List<Record> getConfigByBusiness(int business, int type){
        return Db.find("SELECT * FROM " + Constant.Table.TABLE_BUSINESS_AUTH_CONFIG + " WHERE "
                + BusinessAuthConfig.CONFIG_TYPE + "=" + type + " AND " + BusinessAuthConfig.CREATOR_ORG_ID + "="
                + InterfaceUtil.getOrgId() + " AND " + BusinessAuthConfig.CONFIG_BUSINESS + "=?", business);
    }

    public String getInitDataCityPagerSelectSql(int config_business_id, int creator_org_id){
        String sql = " FROM business_auth_config bac  LEFT JOIN "
                + " (select * from organization where id=CityCode) org ON bac.config_type_id=org.id "
                + " WHERE bac.config_business_id=" + config_business_id + " and bac.creator_org_id=" + creator_org_id
                + " and bac.config_type=1";
        return sql;
    }

    public Page<Record> getCityPagerForRegular(int pageNumber, int pageSize, int config_business_id, int creator_org_id,
            ConcurrentHashMap<String, String> map){
        QueryHelper helper = new QueryHelper("SELECT bac.id,org.NumCode,org.DisplayName",
                " business_auth_config bac  LEFT JOIN  "
                        + "(select * from organization where id=CityCode) org ON bac.config_type_id=org.id ");
        helper.addCondition("bac.config_business_id=? and bac.creator_org_id=? and bac.config_type=1 ",
                            config_business_id, creator_org_id);
        helper.addCondition(map.containsKey("keywordCity"), " (org.NumCode LIKE ? OR org.DisplayName LIKE ?)",
                            "%" + map.get("keywordCity") + "%", "%" + map.get("keywordCity") + "%");
        helper.addOrderProperty("  CONVERT( org.DisplayName USING gbk )  ", true);
        Page<Record> page = Db.paginate(pageNumber, pageSize, helper.getSelect(), helper.getSqlExceptSelect());
        return page;
    }

    public Page<Record> getStorePagerForRegular(int pageNumber, int pageSize, int config_business_id,
            int creator_org_id, ConcurrentHashMap<String, String> map){
        QueryHelper helper = new QueryHelper("SELECT bac.id,org.NumCode,org.DisplayName",
                " business_auth_config bac  LEFT JOIN  " + " organization org ON bac.config_type_id=org.id  ");
        helper.addCondition("bac.config_business_id=? and bac.creator_org_id=? and bac.config_type=2 ",
                            config_business_id, creator_org_id);
        helper.addCondition(map.containsKey("keywordOrg"), " (org.NumCode LIKE ? OR org.DisplayName LIKE ?)",
                            "%" + map.get("keywordOrg") + "%", "%" + map.get("keywordOrg") + "%");
        Page<Record> page = Db.paginate(pageNumber, pageSize, helper.getSelect(), helper.getSqlExceptSelect());
        return page;
    }

    public Page<Record> getMemberPagerForRegular(int pageNumber, int pageSize, int config_business_id,
            int creator_org_id, ConcurrentHashMap<String, String> map){
        QueryHelper helper = new QueryHelper(
                " SELECT member.user_name,member.emp_code,member.mobile,member.name,bac.id",
                " business_auth_config bac  LEFT JOIN  " + " member_org member ON bac.config_type_id=member.id   ");
        helper.addCondition("bac.config_business_id=? and bac.creator_org_id=? and bac.config_type=3 ",
                            config_business_id, creator_org_id);
        helper.addCondition(map.containsKey("keywordMember"),
                            " (member.user_name LIKE ? OR member.emp_code LIKE ? OR member.name LIKE ?)",
                            "%" + map.get("keywordMember") + "%", "%" + map.get("keywordMember") + "%",
                            "%" + map.get("keywordMember") + "%");
        Page<Record> page = Db.paginate(pageNumber, pageSize, helper.getSelect(), helper.getSqlExceptSelect());
        return page;
    }

    public Page<Record> getChannelClassPagerForRegular(int pageNumber, int pageSize, int config_business_id,
            int creator_org_id, ConcurrentHashMap<String, String> map){
        QueryHelper helper = new QueryHelper(" SELECT oc.WebsiteId,oc.class_name,bac.id,org.DisplayName",
                " business_auth_config bac  LEFT JOIN  " + " organization_class oc ON bac.config_type_id=oc.id   LEFT JOIN organization org on bac.city_org_id=org.id");
        helper.addCondition("bac.config_business_id=? and bac.creator_org_id=? and bac.config_type=4 ",
                            config_business_id, creator_org_id);
        helper.addCondition(map.containsKey("keywordChannelClass"), " (oc.WebsiteId LIKE ? OR oc.class_name LIKE ? )",
                            "%" + map.get("keywordChannelClass") + "%", "%" + map.get("keywordChannelClass") + "%");
        Page<Record> page = Db.paginate(pageNumber, pageSize, helper.getSelect(), helper.getSqlExceptSelect());
        return page;
    }

    public Page<Record> getChannelClusterPagerForRegular(int pageNumber, int pageSize, int config_business_id,
            int creator_org_id, ConcurrentHashMap<String, String> map){
        QueryHelper helper = new QueryHelper(" SELECT oc.WebsiteId,oc.class_name,bac.id,org.DisplayName",
                " business_auth_config bac  LEFT JOIN  " + " organization_class oc ON bac.config_type_id=oc.id   LEFT JOIN organization org on bac.city_org_id=org.id");
        helper.addCondition("bac.config_business_id=? and bac.creator_org_id=? and bac.config_type=5 ",
                            config_business_id, creator_org_id);
        helper.addCondition(map.containsKey("keywordChannelCluster"), " (oc.WebsiteId LIKE ? OR oc.class_name LIKE ? )",
                            "%" + map.get("keywordChannelCluster") + "%", "%" + map.get("keywordChannelCluster") + "%");
        Page<Record> page = Db.paginate(pageNumber, pageSize, helper.getSelect(), helper.getSqlExceptSelect());
        return page;
    }

    public Page<Record> getChannelTypePagerForRegular(int pageNumber, int pageSize, int config_business_id,
            int creator_org_id, ConcurrentHashMap<String, String> map){
        QueryHelper helper = new QueryHelper(" SELECT oc.WebsiteId,oc.class_name,bac.id,org.DisplayName",
                " business_auth_config bac  LEFT JOIN  " + " organization_class oc ON bac.config_type_id=oc.id   LEFT JOIN organization org on bac.city_org_id=org.id");
        helper.addCondition("bac.config_business_id=? and bac.creator_org_id=? and bac.config_type=6 ",
                            config_business_id, creator_org_id);
        helper.addCondition(map.containsKey("keywordChannelType"), " (oc.WebsiteId LIKE ? OR oc.class_name LIKE ? )",
                            "%" + map.get("keywordChannelType") + "%", "%" + map.get("keywordChannelType") + "%");
        Page<Record> page = Db.paginate(pageNumber, pageSize, helper.getSelect(), helper.getSqlExceptSelect());
        return page;
    }

    public String getInitDataStorePagerSelectSql(int config_business_id, int creator_org_id){
        String sql = " FROM business_auth_config bac "
                + " LEFT JOIN organization org ON bac.config_type_id=org.id where bac.config_business_id="
                + config_business_id + " and bac.creator_org_id=" + creator_org_id + " and bac.config_type=2";
        return sql;
    }

    public String getInitDataMemberPagerSelectSql(int config_business_id, int creator_org_id){
        String sql = " FROM business_auth_config bac "
                + " LEFT JOIN member_org org ON bac.config_type_id=org.id where bac.config_business_id="
                + config_business_id + " and bac.creator_org_id=" + creator_org_id + " and bac.config_type=3";
        return sql;
    }

    public int deleteAllMemberForBusinessAuthConfig(int type, int configBusiness, int configBusinessId,
            int creatorOrgId){
        String deleteSql = "delete from business_auth_config where config_type=? AND config_business=? "
                + "AND config_business_id=? AND creator_org_id=?";
        return Db.update(deleteSql, type, configBusiness, configBusinessId, creatorOrgId);
    }

    public int deleteAllMemberForBusinessAuthConfigTemp(int type, String flowId){
        String deleteSql = "delete from business_auth_config_temp where flow_id=? AND config_type=? ";
        return Db.update(deleteSql, flowId, type);
    }

    /**
     * @Title: getThemeList
     * @Description:获取主题模块数据（泛店员权限配置用）
     * @return List<Record>
     */
    public List<Record> getThemeList(){
        String sql = "select id,name from themes where enabled=1 and type!=5";
        return Db.find(sql);
    }

    /**
     * @Title: saveSpreadMemberConfig
     * @Description:保存泛店员配置数据，从临时表来和参数组合
     * @param business
     * @param flowId
     * @param ids
     * @return boolean
     */
    public boolean saveSpreadMemberConfig(int business, String flowId, Integer[] ids){
        int creator_org_id = InterfaceUtil.getOrgId();
        Date now = new Date();
        // 1.1获取临时表保存的type和type_id，如果没有就不让保存
        List<Record> records = Db.find("SELECT * FROM " + Constant.Table.TABLE_BUSINESS_AUTH_CONFIG_TEMP + " WHERE "
                + BusinessAuthConfig.FLOW_ID + "=" + flowId);
        if(null == records || records.size() == 0){
            return false;
        }
        // 2.删除原来的
        // String deleteSQL = "DELETE FROM
        // "+Constant.Table.TABLE_BUSINESS_AUTH_CONFIG+" WHERE
        // "+BusinessAuthConfig.CREATOR_ORG_ID+"=? AND
        // "+BusinessAuthConfig.CONFIG_BUSINESS+"=? AND
        // "+BusinessAuthConfig.CONFIG_BUSINESS_ID+"=?";
        // for(int id:ids){
        // Db.update(deleteSQL,creator_org_id,business,id);
        // }
        // 3.一条一条插入
        StringBuffer sb = new StringBuffer();
        sb.append("INSERT INTO " + Constant.Table.TABLE_SPREAD_MEMBER_AUTH_CONFIG + " ("
                + SpreadMemberBusinessAuthConfig.CONFIG_TYPE + "," + SpreadMemberBusinessAuthConfig.CONFIG_TYPE_ID + ","
                + SpreadMemberBusinessAuthConfig.CONFIG_BUSINESS + ","
                + SpreadMemberBusinessAuthConfig.CONFIG_BUSINESS_ID + ","
                + SpreadMemberBusinessAuthConfig.CREATOR_ORG_ID + "," + SpreadMemberBusinessAuthConfig.UPDATED_TIME+ "," + SpreadMemberBusinessAuthConfig.CITY_ORG_ID
                + ") VALUES(?,?,?,?,?,?,?)");
        for(int id : ids){
            for(Record record : records){
                // 查询数据是否已存在，存在就直接跳过
                int cityOrgId =record.getInt(BusinessAuthConfigTemp.CITY_ORG_ID);
                String selectExistData = "select * from " + Constant.Table.TABLE_SPREAD_MEMBER_AUTH_CONFIG
                        + " WHERE config_type=? AND config_type_id=?"
                        + " AND config_business=? AND config_business_id=? AND creator_org_id=?  AND city_org_id=? ";
                Record exist = Db.findFirst(selectExistData, record.getInt(BusinessAuthConfig.CONFIG_TYPE),
                                            record.getInt(BusinessAuthConfig.CONFIG_TYPE_ID), business, id,
                                            creator_org_id,cityOrgId);
                if(exist != null && exist.getInt("id") > 0){
                    continue;
                }
                Db.update(sb.toString(), record.getInt(BusinessAuthConfigTemp.CONFIG_TYPE),
                          record.getInt(BusinessAuthConfigTemp.CONFIG_TYPE_ID), business, id, creator_org_id, now,cityOrgId);
            }
        }
        // 3.删除临时表数据，防止数据量太大
        // 不删除，因为可能保存之后还想另外再选择保存，比如大类：Db.update("DELETE FROM
        // "+Constant.Table.TABLE_BUSINESS_AUTH_CONFIG_TEMP + " WHERE
        // "+BusinessAuthConfig.FLOW_ID+"=?",flowId);
        return true;
    }

    /**
     * @Title: getSpreadMemberSqlExceptSelect
     * @Description:TODO
     * @param searchInfo
     * @return String
     */
    public String getSpreadMemberThemeSqlExceptSelect(ConcurrentHashMap<String, String> searchInfo){
        String sqlExceptSelect = " FROM " + Constant.Table.TABLE_SPREAD_MEMBER_AUTH_CONFIG
                + " smac LEFT JOIN themes t ON t.id=smac.config_business_id  LEFT JOIN organization o ON smac.creator_org_id=o.id  WHERE smac.config_business="
                + Constant.SpreadMemberAuthConfigBusinessType.THEME + " AND smac.creator_org_id IN "+InterfaceUtil.getChlidOrgIdSql(InterfaceUtil.getOrgId(),3,true)+" AND t.enabled=1";

        for(Entry<String, String> item : searchInfo.entrySet()){
            sqlExceptSelect += buildSpreadMemberThemeQuery(item);
        }

        sqlExceptSelect += "  GROUP BY smac.config_business_id,o.DisplayName ";
        sqlExceptSelect += "  ORDER BY updated_time DESC";
        return sqlExceptSelect;
    }

    /**
     * @Title: buildSpreadMemberThemeQuery
     * @Description:TODO
     * @param item
     * @return String
     */
    private String buildSpreadMemberThemeQuery(Entry<String, String> item){
        if("theme_name".equalsIgnoreCase(item.getKey())){
            if(StrKit.notBlank(item.getKey())){
                return " AND t.name LIKE '%" + item.getValue() + "%'";
            }
        }
        // 主题只有管理员能创建和配置授权
        // if("org_id".equalsIgnoreCase(item.getKey())){
        // return " and bac.creator_org_id in("
        // + InterfaceUtil.getChlidOrgIdSql(Integer.parseInt(item.getValue()),
        // Constant.MAX_ORG_LEVEL, true)
        // + ") ";
        // }
        return " ";
    }

    /**
     * @Title: getSpreadMemberSqlSelect
     * @Description:TODO
     * @return String
     */
    public String getSpreadMemberThemeSqlSelect(){
        return "SELECT smac.id as config_id,smac.config_business,smac.config_business_id,smac.creator_org_id,t.name as theme_name,o.DisplayName";
    }

    /**
     * @Title: deleteSpreadMemberAuthConfig
     * @Description:TODO
     * @param config_business_id
     * @param creator_org_id
     * @return int
     */
    public int deleteSpreadMemberAuthConfig(int config_business_id, int creator_org_id){
        String sql = "DELETE FROM " + Constant.Table.TABLE_SPREAD_MEMBER_AUTH_CONFIG
                + " WHERE config_business_id=? AND creator_org_id=?";
        int result = Db.update(sql, config_business_id, creator_org_id);
        return result;
    }

    /**
     * @Title: getSpreadMemberChannelTypePagerForRegular
     * @Description:TODO
     * @param pageNumber
     * @param pageSize
     * @param config_business_id
     * @param creator_org_id
     * @param map
     * @return Page<Record>
     */
    public Page<Record> getSpreadMemberChannelTypePagerForRegular(int pageNumber, int pageSize, int config_business_id,
            int creator_org_id, ConcurrentHashMap<String, String> map){
        QueryHelper helper = new QueryHelper(" SELECT oc.WebsiteId,oc.class_name,bac.id,o.DisplayName",
                Constant.Table.TABLE_SPREAD_MEMBER_AUTH_CONFIG + " bac  LEFT JOIN  "
                        + " organization_class oc ON bac.config_type_id=oc.id  LEFT JOIN organization o ON bac.city_org_id=o.id ");
        helper.addCondition("bac.config_business_id=? and bac.creator_org_id=? and bac.config_type=6 AND bac.city_org_id IN "+InterfaceUtil.getChlidOrgIdSql(InterfaceUtil.getOrgId(),Constant.MAX_ORG_LEVEL,false),
                            config_business_id, creator_org_id);
        helper.addCondition(map.containsKey("keywordChannelType"), " (oc.WebsiteId = ? OR oc.class_name LIKE ? OR o.DisplayName LIKE ? )",
                            map.get("keywordChannelType"), "%" + map.get("keywordChannelType") + "%", "%" + map.get("keywordChannelType") + "%");
        Page<Record> page = Db.paginate(pageNumber, pageSize, helper.getSelect(), helper.getSqlExceptSelect());
        return page;
    }



    /**
     * @Title: getSpreadMemberChannelTypePagerForRegular
     * @Description:TODO
     * @param pageNumber
     * @param pageSize
     * @param config_business_id
     * @param creator_org_id
     * @param map
     * @return Page<Record>
     */
    public Page<Record> getSpreadMemberCityPagerForRegular(int pageNumber, int pageSize, int config_business_id,
                                                                  int creator_org_id, ConcurrentHashMap<String, String> map){
        QueryHelper helper = new QueryHelper(" SELECT sc.id,org.DisplayName,org.NumCode ",
                " spread_member_auth_config sc LEFT JOIN organization org ON sc.config_type_id=org.id  ");
        helper.addCondition(" sc.config_type = 1 AND sc.config_business_id=? AND sc.creator_org_id=?",config_business_id,creator_org_id);
        helper.addCondition(map.containsKey("keywordCity"), " (org.NumCode = ? OR org.DisplayName LIKE ?)",
                map.get("keywordCity"), "%" + map.get("keywordCity") + "%");
        Page<Record> page = Db.paginate(pageNumber, pageSize, helper.getSelect(), helper.getSqlExceptSelect());
        return page;
    }




    /**
     * @Title: getSpreadMemberChannelTypePagerForRegular
     * @Description:TODO
     * @param pageNumber
     * @param pageSize
     * @param config_business_id
     * @param creator_org_id
     * @param map
     * @return Page<Record>
     */
    public Page<Record> getSpreadMemberStorePagerForRegular(int pageNumber, int pageSize, int config_business_id,
                                                           int creator_org_id, ConcurrentHashMap<String, String> map){
        QueryHelper helper = new QueryHelper(" SELECT sc.id,org.DisplayName,org.NumCode ",
                " spread_member_auth_config sc LEFT JOIN organization org ON sc.config_type_id=org.id  ");
        helper.addCondition(" sc.config_type = 2 AND sc.config_business_id=? AND sc.creator_org_id=?",config_business_id,creator_org_id);
        helper.addCondition(map.containsKey("keywordOrg"), " (org.NumCode=? OR org.DisplayName LIKE ?)",
                map.get("keywordOrg"), "%" + map.get("keywordOrg") + "%");
        Page<Record> page = Db.paginate(pageNumber, pageSize, helper.getSelect(), helper.getSqlExceptSelect());
        return page;
    }




    /**
     * @Title: getSpreadMemberChannelTypePagerForRegular
     * @Description:TODO
     * @param pageNumber
     * @param pageSize
     * @param config_business_id
     * @param creator_org_id
     * @param map
     * @return Page<Record>
     */
    public Page<Record> getSpreadMemberPagerForRegular(int pageNumber, int pageSize, int config_business_id,
                                                            int creator_org_id, ConcurrentHashMap<String, String> map){
        QueryHelper helper = new QueryHelper(
                " SELECT member.user_name,member.emp_code,member.mobile,member.name,bac.id",
                " spread_member_auth_config bac  LEFT JOIN  " + " member_org member ON bac.config_type_id=member.id   ");
        helper.addCondition("bac.config_business_id=? and bac.creator_org_id=? and bac.config_type=3 ",
                config_business_id, creator_org_id);
        helper.addCondition(map.containsKey("keywordMember"),
                " (member.user_name ==? OR member.emp_code LIKE ? OR member.name LIKE ?)",
                map.get("keywordMember"), "%" + map.get("keywordMember") + "%",
                "%" + map.get("keywordMember") + "%");
        Page<Record> page = Db.paginate(pageNumber, pageSize, helper.getSelect(), helper.getSqlExceptSelect());
        return page;
    }

    /**
     * 保存到临时表
     * @param flow_id
     * @param type
     * @param ids
     * @param citys
     * @return
     */
    public boolean saveByTypeTemp(String flow_id, int type, Integer[] ids,Integer[] citys){
        for(int id : ids){
            // 查询数据是否已存在，存在就直接跳过
            if(TYPE_CHANNEL_TYPE == type){
                for (Integer cityOrgId : citys) {
                    BusinessAuthConfig.dao.saveATemp(flow_id, type, id,cityOrgId);
                }
            }else if(TYPE_CHANNEL_CLASS ==type || TYPE_CHANNEL_CLUSTER ==type){//渠道大类和渠道簇目前没加地市限制，所以由后台获取地市，以后如果加上了，就可以跟渠道小类统一，由前端传来
                int my_org_id = InterfaceUtil.getOrgId();
                List<Organization> cityList = Organization.dao.getOrganizationCityList(my_org_id);
                for (Organization org:cityList){
                    BusinessAuthConfig.dao.saveATemp(flow_id, type, id,org.getInt(Organization.ID));
                }
            }else {
                BusinessAuthConfig.dao.saveATemp(flow_id, type, id,0);
            }
        }
        return true;
    }
    /**
     * 保存到临时表
     * @param flow_id
     * @param type
     * @param ids
     * @return
     */
    public boolean saveByTypeTemp(String flow_id, int type, Integer[] ids){
        StringBuffer sb = new StringBuffer();
        sb.append("INSERT INTO " + Constant.Table.TABLE_BUSINESS_AUTH_CONFIG_TEMP + " (" + BusinessAuthConfig.FLOW_ID
                + "," + BusinessAuthConfig.CONFIG_TYPE + "," + BusinessAuthConfig.CONFIG_TYPE_ID + ") VALUES(?,?,?)");
        for(int id : ids){
            // 查询数据是否已存在，存在就直接跳过
            String selectExistData = "select * from " + Constant.Table.TABLE_BUSINESS_AUTH_CONFIG_TEMP
                    + " WHERE flow_id=? AND config_type=?" + " AND config_type_id=? ";
            Record record = Db.findFirst(selectExistData, flow_id, type, id);
            if(record != null && record.getInt("id") > 0){
                continue;
            }
            Db.update(sb.toString(), flow_id, type, id);
        }
        return true;
    }
    /**
     * @Title: saveSpreadMemberByType
     * @Description:泛店员业务授权:编辑时新增渠道（小类）授权配置
     * @param type
     * @param ids
     * @param business
     * @param businessId
     * @param creatorOrgId
     * @return boolean
     */
    public boolean saveSpreadMemberByType(int type, Integer[] ids, int business, int businessId, int creatorOrgId){
        StringBuffer sb = new StringBuffer();
        Date now = new Date();
        sb.append("INSERT INTO " + Constant.Table.TABLE_SPREAD_MEMBER_AUTH_CONFIG + " ("
                + BusinessAuthConfig.CONFIG_TYPE + "," + BusinessAuthConfig.CONFIG_TYPE_ID + ","
                + BusinessAuthConfig.CONFIG_BUSINESS + "," + "" + BusinessAuthConfig.CONFIG_BUSINESS_ID + ","
                + BusinessAuthConfig.CREATOR_ORG_ID + "," + BusinessAuthConfig.UPDATED_TIME + ") VALUES(?,?,?,?,?,?)");
        for(int id : ids){
            // 查询数据是否已存在，存在就直接跳过
            String selectExistData = "select * from " + Constant.Table.TABLE_SPREAD_MEMBER_AUTH_CONFIG
                    + " WHERE config_type=? AND config_type_id=?"
                    + " AND config_business=? AND config_business_id=? AND creator_org_id=? ";
            Record record = Db.findFirst(selectExistData, type, id, business, businessId, creatorOrgId);
            if(record != null && record.getInt("id") > 0){
                continue;
            }
            Db.update(sb.toString(), type, id, business, businessId, creatorOrgId, now);
        }
        return true;
    }

    /**
     * @Title: deleteSrpeadMemberAuthConfigByType
     * @Description:TODO
     * @param ids
     * @return boolean
     */
    public boolean deleteSrpeadMemberAuthConfigByType(Integer[] ids){
        StringBuffer sb = new StringBuffer();
        sb.append("DELETE FROM " + Constant.Table.TABLE_SPREAD_MEMBER_AUTH_CONFIG + " WHERE id in(");
        if(ids.length > 0){
            for(int i = 0; i < ids.length; i++){
                if(i == ids.length - 1){
                    sb.append("?");
                } else{
                    sb.append("?,");
                }
            }
            sb.append(")");
        } else{
            return false;
        }
        return Db.update(sb.toString(), (Object[])ids) > 0;
    }

    /**
     * @Title: getSpreadMemberBusinessTypeList
     * @Description:从基础数据配置(sys_code_value表)获取泛店员业务类型配置值
     * @return List<Record>
     */
    public List<Record> getSpreadMemberBusinessTypeList(){
        List<Record> list = SysCodeType.dao.getCodeValueByTypeCode(Constant.ACTIVITY_TYPE_SYS_CODE);
        List<Record> businessTypeList = SysCodeType.dao
                .getCodeValueByTypeCode(Constant.SPREAD_MEMBER_BUS_TYPE_SYS_CODE);
        list.addAll(businessTypeList);
        return list;
    }

    /**
     * @Title: getSqlExceptSelectForSpreadMemberBusinessType
     * @Description:封装泛店员根据业务类型值，获取和查询业务列表数据的脚本，也提供了搜索全部功能，若需要，打开注释即可
     * @param searchInfo
     * @param businessType
     * @return String
     */
    public String getSqlExceptSelectForSpreadMemberBusinessType(ConcurrentHashMap<String, String> searchInfo,
            int businessType){
        String sqlExceptSelect = " FROM (";

        if(businessType >= 0){// 根据传入业务类型获取相关业务数据
            sqlExceptSelect += getSqlExceptSelectForOneBusiness(searchInfo, businessType);
        }
        // else{// 泛店员获取全部类型的已授权业务数据，考虑到搜索全部数据速度慢，暂时不用这个功能，等实在需要再打开
        // sqlExceptSelect += getSqlExceptSelectForAllBusiness(searchInfo,
        // businessType);
        // }

        sqlExceptSelect += ") AS table_s ORDER BY creator_org_id ASC,updated_time DESC";

        return sqlExceptSelect;
    }

    /**
     * @Title: getSqlExceptSelectForAllBusiness
     * @Description:泛店员获取全部类型的已授权业务数据，考虑到搜索全部数据速度慢，暂时不用这个功能，等实在需要再打开
     * @param searchInfo
     * @param businessType
     * @return String
     */
    private String getSqlExceptSelectForAllBusiness(ConcurrentHashMap<String, String> searchInfo, int businessType){
        List<Record> allBus = getSpreadMemberBusinessTypeList();
        String sqlExceptSelect = "";
        int index = 0;
        int busValue = 0;

        for(Record r : allBus){
            if(index != 0){
                sqlExceptSelect += " UNION ALL ";
            }

            if(StrKit.notBlank(r.getStr("value"))){
                busValue = Integer.parseInt(r.getStr("value"));

                searchInfo.put("list_select_type", r.getStr("value"));
            }

            sqlExceptSelect += getSqlExceptSelectForOneBusiness(searchInfo, busValue);

            index++;
        }

        return sqlExceptSelect;
    }

    /**
     * @param searchInfo
     * @Title: getSqlExceptSelectForOneBusiness
     * @Description:TODO
     * @param businessType
     * @return String
     */
    private String getSqlExceptSelectForOneBusiness(ConcurrentHashMap<String, String> searchInfo, int businessType){
        String sqlExceptSelect = "SELECT sys_code.name AS type_name, bus_temp.name, o.DisplayName, bac.creator_org_id, bac.config_business_id, bac.config_business, bac.updated_time FROM spread_member_auth_config bac LEFT JOIN ( SELECT sv.name, sv.value FROM sys_code_value sv LEFT JOIN sys_code_type st ON st.id = sv.type_id WHERE st.code = '"
                + getBusinessTypeCode(businessType)
                + "' AND st.is_deleted = 0 AND sv.is_deleted = 0 ) AS sys_code ON bac.config_business = sys_code.value LEFT JOIN organization o ON bac.creator_org_id = o.id LEFT JOIN ";

        sqlExceptSelect += getSqlExceptSelectByBusinessType(businessType);

        for(Entry<String, String> item : searchInfo.entrySet()){
            sqlExceptSelect += buildQueryForSpreadMemberBusiness(item, businessType);
        }

        sqlExceptSelect += " GROUP BY bac.config_business_id, bac.creator_org_id";

        return sqlExceptSelect;
    }

    /**
     * 店长店员业务授权列表页面：获取已配置的非资费类配置数据：选号入网等其他业务
     * @param searchInfo
     * @param businessType
     * @return
     */
    private String getSqlExceptSelect4GeneralAuth(ConcurrentHashMap<String, String> searchInfo, int businessType){
        String sqlExceptSelect = "SELECT sys_code.name AS type_name, bus_temp.name, o.DisplayName, bac.creator_org_id, bac.config_business_id, bac.config_business, bac.updated_time FROM business_auth_config bac LEFT JOIN ( SELECT sv.name, sv.value FROM sys_code_value sv LEFT JOIN sys_code_type st ON st.id = sv.type_id WHERE st.code = '"
                + getBusinessTypeCode4GeneralAuth(businessType)
                + "' AND st.is_deleted = 0 AND sv.is_deleted = 0 ) AS sys_code ON bac.config_business = sys_code.value LEFT JOIN organization o ON bac.creator_org_id = o.id LEFT JOIN ";

        sqlExceptSelect += getSqlExceptSelectByBusinessType4GeneralAuth(businessType);

        for(Entry<String, String> item : searchInfo.entrySet()){
            sqlExceptSelect += buildQueryForSpreadMemberBusiness(item, businessType);
        }

        sqlExceptSelect += " GROUP BY bac.config_business_id, bac.creator_org_id";

        return sqlExceptSelect;
    }

    /**
     * @Title: getSqlExceptSelectByBusinessType
     * @Description:TODO
     * @param businessType
     * @return String
     */
    private String getSqlExceptSelectByBusinessType(int businessType){
        String sql = "";
        if(businessType < Constant.SM_BUSINESS_TYPE_START){
            sql = Tariff.dao.getSqlExceptSelect();// 资费类业务
        } else{
            switch(businessType){
                case Constant.SpreadMemberAuthConfigBusinessType.ZDXS:// 终端销售
                    sql = Product.dao.getSqlExceptSelect();
                    break;
                case Constant.SpreadMemberAuthConfigBusinessType.KDYY:// 大市场宽带预约
                    sql = Broadband.dao.getSqlExceptSelect(Broadband.BD_SCOPE_YY);
                    break;
                case Constant.SpreadMemberAuthConfigBusinessType.KDKH:// 大市场宽带开户
                    sql = Broadband.dao.getSqlExceptSelect(Broadband.BD_SCOPE_KH);
                    break;
                case Constant.SpreadMemberAuthConfigBusinessType.XHRW:// 选号入网，代表全号段选号入网和选号入网两种业务，因为客户端取这两种业务套餐时的传参一模一样
                    sql = Package.dao.getSqlExceptSelect(Package.PG_TYPE_XHRW);
                    break;
                case Constant.SpreadMemberAuthConfigBusinessType.YXHDXHRW:// 营销活动选号入网
                    sql = Package.dao.getSqlExceptSelect(Package.PG_TYPE_PH_YXHDXHRW);
                    break;
                default:
                    break;
            }
        }

        return sql;
    }

    /**
     * 店长店员业务授权：选号入网、营销活动选号入网。后续这里添加宽带预约，宽带开户
     * @param businessType
     * @return
     */
    private String getSqlExceptSelectByBusinessType4GeneralAuth(int businessType){
        String sql = "";

            switch(businessType){
                case Constant.GeneralMemberAuthConfigBusinessType.XHRW:// 选号入网，代表全号段选号入网和选号入网两种业务，因为客户端取这两种业务套餐时的传参一模一样
                    sql = Package.dao.getSqlExceptSelect(Package.PG_TYPE_XHRW);
                    break;
                case Constant.GeneralMemberAuthConfigBusinessType.YXHDXHRW:// 营销活动选号入网
                    sql = Package.dao.getSqlExceptSelect(Package.PG_TYPE_PH_YXHDXHRW);
                    break;
                default:
                    break;
            }


        return sql;
    }

    /**
     * @Title: getBusinessTypeCode
     * @Description:TODO
     * @param businessType
     * @return String
     */
    private String getBusinessTypeCode(int businessType){
        if(businessType < Constant.SM_BUSINESS_TYPE_START){
            return Constant.ACTIVITY_TYPE_SYS_CODE;
        } else{
            return Constant.SPREAD_MEMBER_BUS_TYPE_SYS_CODE;
        }
    }

    /**
     * 店长店员业务授权：业务类型为活动类型+普通业务授权类型
     * @param businessType
     * @return
     */
    private String getBusinessTypeCode4GeneralAuth(int businessType){
        if(businessType < Constant.SM_BUSINESS_TYPE_START){
            return Constant.ACTIVITY_TYPE_SYS_CODE;
        } else{
            return Constant.GENERAL_MEMBER_BUS_TYPE_SYS_CODE;
        }
    }

    /**
     * @Title: buildQueryForSpreadMemberBusiness
     * @Description:普通业务授权，泛店员业务授权共用
     * @param item
     * @param businessType
     * @return String
     */
    private String buildQueryForSpreadMemberBusiness(Entry<String, String> item, int businessType){
        if("list_select_type".equalsIgnoreCase(item.getKey())){
            return " AND bac.config_business =" + item.getValue();
        }
        if("org_id".equalsIgnoreCase(item.getKey())){
            return " AND bac.creator_org_id in("
                    + InterfaceUtil.getChlidOrgIdSql(Integer.parseInt(item.getValue()), Constant.MAX_ORG_LEVEL, true)
                    + ") ";
        }
        if("name".equalsIgnoreCase(item.getKey()) && StrKit.notBlank(item.getValue())){
            return " AND bus_temp.name like '%" + item.getValue() + "%'";
        }

        return " ";
    }

    /**
     * @Title: getSpreadMemberBusinessData
     * @Description:TODO
     * @param businessType
     * @return JSONArray
     */
    public JSONArray getSpreadMemberBusinessData(int businessType){
        JSONArray busDatas = new JSONArray();
        List<Record> busList = null;
        switch(businessType){
            case Constant.SpreadMemberAuthConfigBusinessType.ZDXS:// 终端销售
                busList = Product.dao.getProductList();
                break;
            case Constant.SpreadMemberAuthConfigBusinessType.KDYY:// 大市场宽带预约
                busList = Broadband.dao.getBroadbandListForMarket(Broadband.BD_SCOPE_YY);
                break;
            case Constant.SpreadMemberAuthConfigBusinessType.KDKH:// 大市场宽带开户
                busList = Broadband.dao.getBroadbandListForMarket(Broadband.BD_SCOPE_KH);
                break;
            case Constant.SpreadMemberAuthConfigBusinessType.XHRW:// 选号入网，代表全号段选号入网和选号入网两种业务，因为客户端取这两种业务套餐时的传参一模一样
                busList = Package.dao.getPackageList(Package.PG_TYPE_XHRW);
                break;
            case Constant.SpreadMemberAuthConfigBusinessType.YXHDXHRW:// 营销活动选号入网
                busList = Package.dao.getPackageList(Package.PG_TYPE_PH_YXHDXHRW);
                break;
            default:
                break;
        }
        if(null != busList && busList.size() > 0){
            busDatas = JSONArray.parseArray(JsonKit.toJson(busList));
        }
        return busDatas;
    }

    /**
     * 后台管理员进行业务显示配置时，为普通店员店长配置权限，获取业务套餐列表
     * @param businessType
     * @return
     */
    public JSONArray getBusinessToAuth4GeneralMember(int businessType) {
        JSONArray busDatas = new JSONArray();
        List<Record> busList = null;
        switch (businessType) {
            case Constant.GeneralMemberAuthConfigBusinessType.XHRW:// 选号入网，代表全号段选号入网和选号入网两种业务，因为客户端取这两种业务套餐时的传参一模一样
                busList = Package.dao.getPackageList(Package.PG_TYPE_XHRW);
                break;
            case Constant.GeneralMemberAuthConfigBusinessType.YXHDXHRW:// 营销活动选号入网
                busList = Package.dao.getPackageList(Package.PG_TYPE_PH_YXHDXHRW);
                break;
            default:
                break;
        }
        if (null != busList && busList.size() > 0) {
            busDatas = JSONArray.parseArray(JsonKit.toJson(busList));
        }
        return busDatas;
    }

}
